package com.itlaobing.exam.handler;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Objects;

public class LocalDateTimeHandler implements TypeHandler<LocalDateTime> {

    @Override
    public void setParameter(PreparedStatement ps, int index, LocalDateTime datetime, JdbcType jdbcType) throws SQLException {
        if( Objects.nonNull( datetime ) ) {
            ZonedDateTime zdt = datetime.atZone( ZoneId.systemDefault() );
            Instant x = Instant.from( zdt );
            long millis = x.toEpochMilli() ;
            java.sql.Date date = new java.sql.Date( millis ) ;
            ps.setDate(index, date);
        }
    }

    @Override
    public LocalDateTime getResult( ResultSet rs , String label ) throws SQLException {
        java.sql.Date date = rs.getDate( label );
        return this.of( date );
    }

    @Override
    public LocalDateTime getResult( ResultSet rs , int index ) throws SQLException {
        java.sql.Date date = rs.getDate( index );
        return this.of( date );
    }

    @Override
    public LocalDateTime getResult( CallableStatement cs , int index ) throws SQLException {
        java.sql.Date date = cs.getDate( index );
        return this.of( date );
    }

    private LocalDateTime of( java.sql.Date date ) {
        LocalDateTime dateTime = null ;
        if( date != null ) {
            long millis = date.getTime(); // 从 java.sql.Date实例 中获得 毫秒值
            Instant instant = Instant.ofEpochMilli( millis );
            ZoneId zone = ZoneId.systemDefault() ;
            dateTime = LocalDateTime.ofInstant( instant , zone );
        }
        return dateTime ;
    }

}
